﻿/// <reference path="../jquery-easyui-1.2.6/jquery-1.7.2.min.js" />
/// <reference path="../jquery-easyui-1.2.6/jquery.easyui.min.js" />
/// <reference path="CaculateTableJs.js" />
/// <reference path="../json2.js" />
/// <reference path="trimpath-template.js" />

var stockPage = {};
//功能1 敲回车查询条码信息
//功能2 确认按钮保持所以录入的条码信息
stockPage.entTM = function () {
    var config = { "datalist": "", cacheData: true, cacheHtmlId: "cacheDataDiv", cannotRepterCol: "Tm" };

    //1 keydown 
    this.TmKeyDown = function () {
        jQuery(document).bind('keydown', function (e) {
            if (e) {
                if (e.which == 13) {
                    var tmVal = jQuery("#BarcodeText").val();
                    if (checkTmFormat(tmVal)) {
                        if (checkTmExist(tmVal)) {
                            alert("此条码关联的货品已经入库,操作不能完成");
                        }
                        else {
                            errorMsgDisplay.hideErrMsg();
                            setEntsTableVisable();
                            RequetJson(tmVal);
                            jQuery("#BarcodeText").val("");
                        }
                    }
                    return false;
                }
            }
        })
    };
    // 2 blur event on TmCode
    this.TMBlurEnvent = function () {
        jQuery("#BarcodeText").bind("blur", function () {
            var tmVal = jQuery("#BarcodeText").val();
            var rd = parseInt(Math.random(1) * 10000);
            tmVal == "" || tmVal == "undefined" ? errorMsgDisplay.requiredMsg({ id: "tmErrMsg", msg: "请录入条码" }) : errorMsgDisplay.hideErrMsg();
        });
    };

    this.TmfocusEvent = function () {
        jQuery("#BarcodeText").focus(function () {
            $(this).val("");
        });
    }

    this.TmfocusCur = function () {
        jQuery("#BarcodeText").focus();
    }

    //3 request json obj
    var RequetJson = function (tmVal) {
        var rd = parseInt(Math.random(1) * 10000);
        jQuery.ajax({ async: false,
            type: "GET",
            cache: false,
            url: "../handlecontrol/stockin.ashx?func=EntTMCode&rd=" + rd,
            data: { "tm": tmVal },
            success: successProcess,
            error: errorProcess
        });
    };

    function successProcess(data) {
        var jsonObj = JSON.parse(data);
        if (jsonObj["error"]) {
            errorMsgDisplay.noDataInfo();
            return;
        }
        config["datalist"] = jsonObj;
        jQuery("#stockinTable").caculateTable(config);
    }

    function errorProcess() {
        //console.log("erro");
    }

    //4 Verify tm format
    var checkTmFormat = function (tmVal) {
        if (tmVal == "" || tmVal == 'undefine') {
            errorMsgDisplay.requiredMsg();
            return false;
        }
        return true;
    };

    var checkTmExist = function (tmVal) {
        var exist = "";
        jQuery.ajax({ async: false,
            type: "GET",
            cache: false,
            url: "../handlecontrol/stockin.ashx?func=IsTmExist",
            data: { "tm": tmVal, "rd": parseInt(Math.random(1) * 10000) },
            success: function (data) {
                var obj = JSON.parse(data); exist = obj["exist"];
            },
            error: function () { errorMsgDisplay.noDataInfo(); exist = "Y"; }
        });
        return exist == "Y";
    }

    //5 show verify msg
    var errorMsgDisplay = {
        errMsg: { id: "tmErrMsg", msg: "", style: { "color": "red"} },
        requiredMsg: function (errMsg) {
            this.errMsg.msg = "*请录入条码";
            errorMsgDisplay.commanMsgFun();
        },
        formatErrMsg: function () {
            this.errMsg.msg = "*条码格式不对";
            errorMsgDisplay.commanMsgFun();
        },
        noEntInfo: function () {
            this.errMsg.msg = "*请扫描货品后在按确认入库";
            alert(this.errMsg.msg);
            // errorMsgDisplay.commanMsgFun();
        },
        noDataInfo: function () {
            this.errMsg.msg = "*没有此条码信息";
            errorMsgDisplay.commanMsgFun();
        },
        hideErrMsg: function () {
            var msgDiv = jQuery("#" + this.errMsg.id);
            msgDiv.html("");
            msgDiv.hide();
        },
        commanMsgFun: function () {
            var errMsg = errMsg || this.errMsg;
            var msgDiv = jQuery("#" + this.errMsg.id);
            msgDiv.html("");
            msgDiv.html(this.errMsg.msg);
            msgDiv.css(this.errMsg.style);
            msgDiv.show();
        }

    }

    // empty table 
    function cleanEntsTable() {
        var trs = jQuery("#stockinTable tr");
        if (trs.length > 2) {
            for (var i = 1, len = trs.length; i < len - 1; i++) {
                trs.eq(i).remove();
            }
        }
        trs.last().hide();
        trs.first().hide();
    }

    function setEntsTableVisable() {
        var trs = jQuery("#stockinTable tr");
        trs.last().show();
        trs.first().show();
    }

    //---------------------------------------------------------------------------
    //功能 2 save tmInfo 
    this.btnOK = function () {
        jQuery("#btnOk").bind("click", function () {
            //clear msg 
            errorMsgDisplay.hideErrMsg();
            var id = document.getElementById(config["cacheHtmlId"]);
            if (id) {
                //console.log(id.value);
                var ins = jQuery("#cacheDataDiv").data();
                if (!ins.storagedata) {
                    errorMsgDisplay.noEntInfo();
                    return;
                }
                else if (ins.storagedata.length > 0) {
                    processOkbtn(ins);
                }
                else {
                    canotSubmit();
                }
            }
            else {
                canotSubmit();
            }
        });
    }
    //click ok btn
    function processOkbtn(stockInlist) {
        var stockLs = JSON.stringify(stockInlist);
        //console.log(stockLs);
        var whs = jQuery("#warehouseDrp").find("option:selected").text();
        jQuery.ajax({ async: false,
            type: "POST",
            cache: false,
            url: "../handlecontrol/stockin.ashx?func=StockAdd",
            data: { "stockLs": stockLs, "whs": whs, "rd": parseInt(Math.random(1) * 10000) },
            success: stockInOk,
            error: err
        });

        function stockInOk(data) {
            var jo = JSON.parse(data);
            if (jo["error"]) {
                alert("入库失败！");
            }
            else {
                cleanEntsTable();
                disableBtn();
                $("#stockList").html("");
                $("#stockList").html(TrimPath.processDOMTemplate("stockList_tlp", jo));
            }
        };

        function err(data) {
            //console.log("err");
            alert("入库失败！");
        }

        //disable 1 删除link 2 ok按钮
        function disableBtn() {
            jQuery("#stockinTable").find("a[id=delete]").unbind("click").bind("click", function () { alert("该笔数据已经入库，不能进行该操作"); return false; });
            jQuery("#btnOk").unbind("click").bind("click", function () { alert("该笔数据已经入库，不能进行该操作"); return false; });

        }
    }

    //alert con't submit
    function canotSubmit() {
        return;
    }
};

stockPage.BildetailTotal = {"qty":0,"price":0};

stockPage.Bildetail = function (bil) {
    if (bil) {
        jQuery.getJSON("../handlecontrol/stockin.ashx?func=GetStockBilDetail", { bil: bil, rn: parseInt(Math.random(1) * 10000) }, function (data) {
            stockPage.BildetailTotal.qty = 0;
            stockPage.BildetailTotal.price = 0;
            if (data != null && data.list != null) {
                for (var i = 0, len = data.list.length; i < len; i++) {
                    stockPage.BildetailTotal.qty += data.list[i]["ITDPOS_TRQ"];
                    stockPage.BildetailTotal.price += (data.list[i]["ITDPOS_TRQ"] * data.list[i]["ITHPOS_LSPRI"]);
                }
            }
            $("#stockDetailList").html("");
            $("#stockDetailList").html(TrimPath.processDOMTemplate("stockDetail_tlp", data));
            jQuery("#stockDetailList").dialog({ "title": "入库明细" });
        });
    }
    else {
        alert("没有查询到相关的入库明细信息");
    }
}



stockPage.Intail = function () {
    stockPage.getCurrUserInfo();
    var pageEvent = new stockPage.entTM;
    pageEvent.TMBlurEnvent();
    pageEvent.TmKeyDown();
    pageEvent.TmfocusEvent();
    pageEvent.btnOK();
    stockPage.printPage();
}
stockPage.getCurrUserInfo = function () {

    var getFarmatDt = function (date) {

        var thisYear = date.getFullYear();
        var thisMonth = date.getMonth() + 1;
        //如果月份长度是一位则前面补0   
        if (thisMonth < 10) thisMonth = "0" + thisMonth;

        var thisDay = date.getDate();
        //如果天的长度是一位则前面补0   
        if (thisDay < 10) thisDay = "0" + thisDay;

        var thisHour = date.getHours();
        //如果小时长度是一位则前面补0   
        if (thisHour < 10) thisHour = "0" + thisHour;

        var thisMinute = date.getMinutes();
        //如果分钟长度是一位则前面补0   
        if (thisMinute < 10) thisMinute = "0" + thisMinute;

        var thisSecond = date.getSeconds();
        //如果分钟长度是一位则前面补0   
        if (thisSecond < 10) thisSecond = "0" + thisSecond;
        return thisYear + "-" + thisMonth + "-" + thisDay + " " + thisHour + ":" + thisMinute + ":" + thisSecond;
    }

    jQuery.getJSON("../handlecontrol/stockin.ashx?func=GetWHSInfo", { "rn": parseInt(Math.random(1) * 10000) },
    function (data) {
        var objArr=[];
        if (data != null) {
            objArr = data.list;
        }
        var htmlArr = new Array;
        for (var i = 0, len = objArr.length; i < len; i++) {
            var str = "<option value='" + objArr[i]["WHS_WHS"] + "'>" + objArr[i]["WHS_WHS"] + "</option>";
            htmlArr.push(str);
        }
        
        jQuery("#warehouseDrp").append(htmlArr.join(" "));
    });

    jQuery.getJSON("../handlecontrol/stockin.ashx?func=GetUserDefuatInfo", { "rn": parseInt(Math.random(1) * 10000) },
       function (data) {
           var dt = new Date();
           var defaultWhs = data.user.WHSWHS;

           jQuery("#shipCodeTxt").val(data.user.CII);
           jQuery("#shpNameTxt").val(data.user.CIIDES);
           jQuery("#stockIndateTxt").val(getFarmatDt(dt).substring(0, 10));
       });


}

stockPage.toDefaultDtFormat = function (dt) {
    var dtStr = dt.substring(0, 10);
    return dtStr.replace(/T/, " ");
}

stockPage.printPage = function () {
    jQuery("#btnPrint").bind("click", function () { window.print(); });
}

// 显示条码查询出来的信息
jQuery(function () {
    stockPage.Intail();
});

